<template>
  <div id="users">
    <!-- <bread> -->
    <ubread />
    <!-- 卡片视图 -->
    <el-card>
      <!-- 用户搜索区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" class="input-with-select">
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="adduser">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格区块 -->
      <el-table :data="userList" border style="margin-top: 15px">
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <!-- 修改用户状态 -->
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ccc"
              @change="stat(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 编辑区域、 -->
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="edit(scope.row)"></el-button>
            <!-- 删除 -->
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="del(scope.row)"></el-button>
            <!-- 设置角色-->
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="sett(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 3, 6, 9]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!--  -->

    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <el-form :model="ruleForm" :rules="rules" ref="ref" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户对话框 -->
    <el-dialog title="提示" :visible.sync="editVisible" width="45%">
      <el-form :model="editList" ref="editRef" :rules="rulesFrom" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username" label-width="75px">
          <el-input v-model="editList.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" label-width="75px">
          <el-input v-model="editList.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile" label-width="75px">
          <el-input v-model="editList.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="editAdd">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配角色" :visible.sync="settVisible" width="30%">
      <p>
        <span>当前的用户：{{ list.username }}</span>
      </p>
      <p>
        <span>当前的角色：{{ list.role_name }}</span>
      </p>
      <div>
        <span>分配新的角色：</span>
        <el-select v-model="set" placeholder="请选择">
          <el-option v-for="item in setting" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="set">取 消</el-button>
        <el-button type="primary" @click="settAdd">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import ubread from "../bread.vue";
import usersApi from "..//../api/users";

export default {
  components: {
    ubread
  },
  data() {
    const Email = (rule, value, callback) => {
      const re = /^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\.)+[a-z]{2,}$/;
      if (!re.test(value)) {
        callback(new Error("请输入正确的邮箱规则"));
      } else {
        callback();
      }
    };
    const Moabile = (rule, value, callback) => {
      const hua = /^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/;
      if (!hua.test(value)) {
        callback(new Error("请输入正确的电话格式"));
      } else {
        callback();
      }
    };
    return {
      editVisible: false,
      set: "",
      ruleForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      settVisible: false, //分配权限列表对话框
      setting: [], //分配角色数据
      list: {}, //点击分配权限当前行信息
      dialogVisible: false,
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 3
      },
      total: 0,
      userList: [], //所有数据
      editList: {},
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 10, message: "请输入2到10位字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 10, message: "请输入2到10位字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入用户邮箱", trigger: "blur" },
          { Email, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入用户邮箱", trigger: "blur" },
          { Moabile, trigger: "blur" }
        ]
      },
      rulesFrom: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 10, message: "请输入2到10位字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 10, message: "请输入2到10位字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入用户邮箱", trigger: "blur" },
          { Email, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入用户邮箱", trigger: "blur" },
          { Moabile, trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    add() {
      this.$refs.ref.validate(async el => {
        console.log(el);
        if (el) {
          const { data: res } = await usersApi.add(this.ruleForm);
          console.log(res);
          if (res.meta.status == 201) {
            this.$message.success("添加成功");
            this.dialogVisible = false;
            this.getList();
          } else {
            this.$message.error("添加失败");
          }
        }
      });
    },
    adduser() {
      this.dialogVisible = true;
    },
    async edit(scope) {
      const { data: res } = await usersApi.edit(`${scope.id}`);
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg);
      }
      this.editList = res.data;
      this.editVisible = true;
    },
    editAdd() {
      this.$refs.editRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await usersApi.editAdd(
          this.editList.id,
          this.editList
        );
        if (res.meta.status !== 200) {
          this.$message.error(res.meta.msg);
        }
        this.getList();
      });
      this.editVisible = false;
    },
    async stat(scope) {
      // const { data: res } = await this.$http.put(
      //   `users/${scope.id}/state/${scope.mg_state}`
      // );
      const { data: res } = await usersApi.state(scope.id, scope.mg_state);
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg);
      }
      this.$message.success(res.meta.msg);
      this.getList();
    },
    // 获取所有用户
    async getList() {
      const { data: res } = await usersApi.getList({ params: this.queryInfo });

      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg);
      }
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    // 分页
    handleSizeChange(val) {
      console.log(val);
      this.queryInfo.pagesize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val;
      this.getList();
    },
    // 点击分配权限按钮
    async sett(scope) {
      this.list = scope;
      this.settVisible = true;

      // const { data: res } = await this.$http.get("/roles");
      const { data: res } = await usersApi.sett();
      console.log(res);
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg);
      }
      this.setting = res.data;
    },
    // 点击确定按钮，分配角色
    async settAdd() {
      if (this.set === "") {
        this.$message({
          message: "请选择要分配的角色",
          type: "warning"
        });
      } else {
        // const { data: res } = await this.$http.put(
        //   `users/${this.list.id}/role`,
        //   {
        //     rid: this.list.id
        //   }
        // );
        const { data: res } = await usersApi.settAdd(this.list.id, {
          rid: this.list.id
        });
        if (res.meta.status !== 200) {
          this.$message.error(res.meta.msg);
        }
        this.settVisible = false;
        this.getList();
      }
    },
    async del(scope) {
      const result = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      /*
    	$confirm方法返回的是一个Promise对象，可以通过async/await的方式结束返回值；
    	如果返回值的结果是cancel证明点击的是取消按钮；
    	如果返回值的结果是confirm证明点击的是确定按钮
      */
      if (result === "cancel") {
        // 证明咱们现在点击的是取消按钮
        return;
      } else if (result === "confirm") {
        // 证明点击的是确定按钮
        // const res = await this.$http.delete(`users/${scope.id}`);
        const res = await usersApi.del(scope.id);

        const { meta } = res.data;
        if (meta.status !== 200) {
          this.$message.error(meta.msg);
        } else {
          this.$message.success("用户删除成功");
          // 重新向服务器发起请求，获取最新用户列表数据
          this.getList();
        }
      }
    }
  }
  // 删除用户
};
</script>
<style lang='scss' scoped>
.el-card {
  margin-top: 15px;
}
</style>